package middlewares

import (
	"backend/utils"
	"net/http"
	"strings"

	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
)

func JWTAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		//跳过鉴权
		if c.Request.URL.Path == "/user/login" || c.Request.URL.Path == "/user/feishu/login" || c.Request.URL.Path == "/api/v1/register" {
			c.Next()
			return
		}
		// 从请求头中获取 Authorization 字段
		tokenString := c.GetHeader("Authorization")

		// 检查 Token 是否以 "Bearer " 开头
		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer ") {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
			c.Abort()
			return
		}

		// 提取真正的 Token
		tokenString = strings.TrimPrefix(tokenString, "Bearer ")

		// 验证 Token
		token, err := utils.ParseToken(tokenString)
		if err != nil || !token.Valid {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
			c.Abort()
			return
		}

		// 解析 Token 中的用户名并存入上下文
		if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
			c.Set("email", claims["email"])
		} else {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
			c.Abort()
			return
		}

		//

		c.Next()
		return
	}
}
